package com.zheng.common.aspect;

import com.alibaba.dubbo.rpc.RpcContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RpcLogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(RpcLogAspect.class);

    // 开始时间
    private long starTime = 0L;
    // 结束时间
    private long endTime = 0L;

    @Before("execution(* *..rpc..*.*(..))")
    public void doBeforeInServiceLayer(JoinPoint joinPoint) {
        LOGGER.debug("doBeforeInServiceLayer");
        starTime = System.currentTimeMillis();
    }

    @After("execution(* *..rpc..*.*(..))")
    public void doAfterInServiceLayer(JoinPoint joinPoint) {
        LOGGER.debug("doAfterInServiceLayer");
    }

    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object result = pjp.proceed();
        // 是否是消费端
        boolean consumerSide = RpcContext.getContext().isConsumerSide();
        // 获取最后一次提供方或调用方IP
        String ip = RpcContext.getContext().getRemoteHost();
        // 服务url
        String rpcUrl = RpcContext.getContext().getUrl().getParameter("application");
        LOGGER.info("consumerSide={}, ip={}, url={}", consumerSide, ip, rpcUrl);
        return result;
    }
}
